package com.fc.v2.controller.api;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fc.v2.model.MapObject;
import com.fc.v2.WX.WXUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;

@Api(value = "微信支付API")
@Controller
@RequestMapping("/api/WXPay")
public class AWXPayController {

    private static final Logger log = LoggerFactory.getLogger(AWXPayController.class);

    /**
     * 接受微信支付订单通知
     *
     * @param
     * @param
     * @return
     */
    @ApiOperation(value = "接受微信支付订单通知", notes = "接受微信支付订单通知")
    @PostMapping("/get/notification")
    @ResponseBody
    @Transactional
    public Object getNotification(@RequestBody String notification) throws GeneralSecurityException, IOException {
        System.out.println("notification:  "+notification);
        JSONObject jsonObject = JSONUtil.parseObj(notification);

        byte[] nonce = jsonObject.getByPath("resource.nonce").toString().getBytes(StandardCharsets.UTF_8);
        byte[] associatedData = jsonObject.getByPath("resource.associated_data").toString().getBytes(StandardCharsets.UTF_8);
        String ciphertext = jsonObject.getByPath("resource.ciphertext").toString();
        String res = WXUtil.decryptToString(associatedData, nonce, ciphertext);

        //解密后的resource对象
        JSONObject resource = JSONUtil.parseObj(res);
        System.out.println("解密后的resource:\n"+resource.toStringPretty());

        String trade_state = resource.get("trade_state").toString();
        String orderId = resource.get("out_trade_no").toString();
        String attach = resource.get("attach").toString();
        JSONObject attachObject = JSONUtil.parseObj(attach);

        if(trade_state.equals("SUCCESS")){
            log.debug("收到微信支付应答，SUCCESS");

        }else{
            log.warn("收到微信支付应答，ERROR\n,res:{}", resource.toStringPretty());
        }

        return new MapObject().put("code","SUCCESS").put("message","");
    }
}
